package util;

import java.sql.*;
import java.util.List;

public class DBUtils {
    private Connection connection;
    private PreparedStatement pps;
    private ResultSet resultSet;
    private int count;

    private String url = "jdbc:mysql://localhost:3366/mydb2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai";
    private String userName = "root";
    private String userPass = "123456";

    static {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected Connection getConnection(){
        try{
            connection = DriverManager.getConnection(url,userName,userPass);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return connection;
    }

    protected PreparedStatement getPps(String sql){
        try{
            pps = getConnection().prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return pps;
    }

    protected void param(List list){
        if(list!=null&&list.size()>0){
            for(int i = 0;i<list.size();i++){
                try{
                    pps.setObject(i+1,list.get(i));
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    protected ResultSet query(String sql,List list){
        getPps(sql);
        param(list);
        try{
            resultSet = pps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return resultSet;
    }

    protected ResultSet queryd(String sql){
        getPps(sql);
        try{
            resultSet = pps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return resultSet;
    }

    protected int updata(String sql,List list){
        getPps(sql);
        param(list);
        try{
            count = pps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count;
    }

    protected void closeAll(){
        try{
            if(connection != null){
                connection.close();;
            }
            if (resultSet != null){
                resultSet.close();
            }
            if( pps != null){
                pps.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
